const userSchema = require('../models/user');
const passwordSchema = require('../models/password');
const publishSchema = require('../models/publish');
const qiniu=require('qiniu');
const { v4: uuidv4 } = require('uuid');
const bcrypt = require('bcrypt');
const dayjs=require('dayjs');
const config = require('../config/config');
const user = {
    login: async (ctx, next) => {
        let { phonenumber, password } = ctx.request.body;
       
        await userSchema.find({ phoneNumber: phonenumber }).then(async res => {
            if (!res.length) {
                ctx.body = {
                    code: 404,
                    msg: '用户不存在!'
                }
                return
            } else {
                let data = res[0]
                await passwordSchema.find({ userId: data.userId }).then(async res => {
                    await bcrypt.compare(password, res[0].password).then(flag => {
                        if (flag) {
                            ctx.body = {
                                code: 200,
                                data: {
                                    phoneNumber: data.phoneNumber,
                                    userId: data.userId,
                                    avator: data.avator,
                                    nickName: data.nickName,
                                    birthDay: data.birthDay,
                                    age: data.age,
                                    location: data.location,
                                    gender: data.gender,
                                    currentLocation: data.currentLocation
                                },
                                msg: '登录成功！'
                            }
                            return
                        } else {
                            ctx.body = {
                                code: 201,
                                msg: '密码错误！'
                            }
                        }
                    })
                })
            }
        })
    },
    register: async (ctx, next) => {
        let { phonenumber, password } = ctx.request.body;
       
        await userSchema.find({ phoneNumber: phonenumber }).then(async res => {
           
            if (res.length) {
                ctx.body = {
                    code: 201,
                    msg: '用户已存在！'
                }
                return
            } else {
                const uuid = uuidv4();
                
                await userSchema.create({ phoneNumber: phonenumber, userId: uuid }).then(res => {
                    
                })
                bcrypt.hash(password, config.salt).then(async pass => {
                    
                    await passwordSchema.create({ password: pass, userId: uuid })
                });
                ctx.body = {
                    code: 200,
                    msg: '注册成功！'
                }
                return
            }
        })
    },
    changePass: async (ctx, next) => {
        let { oldPass, newPass, userId } = ctx.request.body;
        
        const res = await passwordSchema.find({ userId: userId })
        
        await bcrypt.compare(oldPass, res[0].password).then(async flag => {
            if (!flag) {
                ctx.body = {
                    code: 201,
                    msg: '原密码错误'
                }
                return
            } else {
                await bcrypt.hash(newPass, config.salt).then(async pass => {
                    res[0].password = pass;
                    await res[0].save();
                })

                ctx.body = {
                    code: 200,
                    msg: '修改成功,请重新登录'
                }

            }
        })


    },
    delAccount: async (ctx, next) => {
        let { pass, userId } = ctx.request.body;
        
        const isRight = await passwordSchema.findOne({ userId: userId });
        
        const correct = await bcrypt.compare(pass, isRight.password)
     
        if (correct) {
            await userSchema.deleteOne({ userId: userId })
            await passwordSchema.deleteOne({ userId: userId })
            ctx.body = {
                code: 200,
                msg: '注销成功！'
            }
        } else {
            ctx.body = {
                code: 201,
                msg: '密码错误！'
            }
            return
        }
        return
    },
    saveSetting: async (ctx, next) => {
    
        const { avator,
            gender,
            birthday,
            location,
            nickName,
            userId,
            currentLocation } = ctx.request.body;
        try {
            const result = await userSchema.findOneAndUpdate({ userId: userId }, { nickName: nickName, location: location, avator: avator, gender: gender, birthDay: birthday, currentLocation: currentLocation }, { new: true })
            
            ctx.body = {
                code: 200,
                msg: '更改成功！',
                data: {
                    avator: result.avator,
                    nickName: result.nickName,
                    birthDay: result.birthDay,
                    location: result.location,
                    gender: result.gender,
                    currentLocation: result.currentLocation,
                    userId: result.userId,
                    phoneNumber: result.phoneNumber
                }

            }
            return;
        } catch (error) {
            console.log(error);
        }

    },
    publish: async (ctx, next) => {
       
        let { passangerSum,
            timestamp,
            Departure,
            Destination,
            message,
            userId,
            avator,
            nickName
        } = ctx.request.body
            timestamp=dayjs(timestamp).format()
        const result = await publishSchema.findOne({ timestamp: timestamp, Departure: Departure, Destination: Destination })
      
        if (result) {
            ctx.body = {
                code: 201,
                msg: '重复发布'
            }
            return
        }else{
            const flag = await publishSchema.create(
            {
                passangerSum: passangerSum,
                timestamp: timestamp,
                Departure: Departure,
                Destination: Destination,
                message: message,
                userId: userId,
                avator: avator,
                nickName:nickName,
            }
        )
       
        ctx.body={
            code:200,
            msg:'发布成功！'
        }
        }
        
    },
    getUptoken:async (ctx,next)=>{
        let ak='cBi0vN5F0OqXl0UDpT8d6nfyNHG7u51pzs2BWFb8'
        let sk='Eth2jFdyfcSrhiGf64u99iN9W26MGMI5RNsIFjTr'
        let bucket='kaiavator'

        let mac=new qiniu.auth.digest.Mac(ak,sk);
        let option={
            scope:bucket,
            expires:3600*24
        }
        let putPolicy=new qiniu.rs.PutPolicy(option)
        let upToken=putPolicy.uploadToken(mac);
        
        if (upToken) {
            ctx.body={
                code:200,
                upToken:upToken,
                msg:'token获取成功'
            }
        }else{
            ctx.body={
                code:201,
                msg:'token获取失败'
            }
        }
    }
}
module.exports = user